package com.ossjk.oa.attendance.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.core.vo.PagePreNextVo;
import com.ossjk.oa.attendance.entity.Attendance;
import com.ossjk.oa.attendance.mapper.AttendanceMapper;
import com.ossjk.oa.attendance.service.IAttendanceService;
import com.ossjk.oa.system.entity.Department;
import com.ossjk.oa.system.service.IDepartmentService;
import com.ossjk.oa.system.service.IEmployeeService;
import com.ossjk.oa.system.vo.EmployeeVo;

/**
 * <p>
 * 考勤 服务实现类
 * </p>
 *
 * @author chair
 * @since 2019-02-03
 */
@Service
public class AttendanceServiceImpl extends ServiceImpl<AttendanceMapper, Attendance> implements IAttendanceService {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	
	@Autowired
	private IEmployeeService iEmployeeService;
	@Autowired
	private IDepartmentService iDepartmentService;

	public PagePreNextVo selectPreNext(String midMth) {

		PagePreNextVo vo = new PagePreNextVo();
		
		String[] strs = midMth.split("-");
		
		Integer mth =Integer.parseInt(strs[0])*100 +Integer.parseInt(strs[1]);
		System.out.println(mth);
		
		Integer tmpX =this.baseMapper.selectPreMth(mth);
		//202005   to 2020-05
		vo.setPre(tmpX==null?" ":(tmpX+"").substring(0, 4)+ "-"+ (tmpX+"").substring( 4)   );
		tmpX =this.baseMapper.selectNextMth(mth);
		vo.setNext(tmpX==null?" ":(tmpX+"").substring(0, 4)+ "-"+ (tmpX+"").substring( 4));
		vo.setCurrent(  (midMth+"").substring(0, 4)+ "-"+ (midMth+"").substring( 4));
		 
		return vo;
	}
	
	
	@Override
	public Page selectVoPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoPage(page, wrapper));
		return page;
	}

	@Override
	public boolean batchImportExcel(File destFile) throws Exception {
		Wrapper wrapper = Condition.create().isWhere(true).eq("e.isdelete", 1);
		Map<String, EmployeeVo> employeeInfoMap = new HashMap();
		Map<String, Department> departmentMap = new HashMap();
		// 查找所有员工信息
		Page<EmployeeVo> page = iEmployeeService.selectVoPage(new Page(1, Integer.MAX_VALUE), wrapper);
		if (!CommonUtil.isBlank(page.getRecords())) {
			for (EmployeeVo employeeVo : page.getRecords()) {
				employeeInfoMap.put(employeeVo.getRname() + "_" + employeeVo.getDname(), employeeVo);
			}
		}
		// 查找所有部門信息
		List<Department> departments = iDepartmentService.selectList(null);
		if (!CommonUtil.isBlank(departments)) {
			for (Department department : departments) {
				departmentMap.put(department.getId(), department);
			}
		}
		// 兼容写法
		Workbook wb = WorkbookFactory.create(new FileInputStream(destFile));
		// 获取第0个sheet
		Sheet sheet = wb.getSheetAt(0);
		// 获取第二行
		Row row = sheet.getRow(1);
		// 统计日期:2019.1.1-2019.1.30
		String cellStr = row.getCell(0).getStringCellValue();
		// 开始时间
		String beginDateStr = cellStr.split(":")[1].split("-")[0];
		// 结束时间
		String endDateStr = cellStr.split(":")[1].split("-")[1];
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
		SimpleDateFormat timeft = new SimpleDateFormat("hh:mm");
		// 开始时间
		Date beginDate = sdf.parse(beginDateStr);
		// 结束时间
		Date endDate = sdf.parse(endDateStr);
		// 最大一天
		int maxDay = CommonUtil.int2(CommonUtil.date0(endDate).substring(6, 8));
		int dataSpace = 3;
		int beginRow = dataSpace - 1;
		int endRow = sheet.getLastRowNum();
		// 插入记录
		List<Attendance> attendances = new ArrayList();

		for (; beginRow < endRow; beginRow += dataSpace) {
			// 用户信息
			String info = sheet.getRow(beginRow).getCell(0).getStringCellValue();
			// 用户信息
			String ename = info.substring(info.indexOf("姓名:") + 3, info.indexOf("部门:")).trim();
			// 部门信息
			String dname = info.substring(info.indexOf("部门:") + 3).trim();
			// 员工信息
			EmployeeVo employeeVo = employeeInfoMap.get(ename + "_" + dname);

			if (CommonUtil.isBlank(employeeVo)) {
				log.info(ename + "_" + dname + " 没有在系统里面");
				continue;
			}
			// 考勤信息
			for (int i = 0; i < maxDay; i++) {
				Attendance attendance = new Attendance();
				// 员工id
				attendance.setEid(employeeVo.getId());
				// 部门id
				attendance.setDid(employeeVo.getDid());
				// 设置年月日
				attendance.setYear(new BigDecimal(CommonUtil.date0(beginDate).substring(0, 4)));
				attendance.setMonth(new BigDecimal(CommonUtil.date0(beginDate).substring(4, 6)));
				attendance.setDay(new BigDecimal((i + 1)));
				// 设置当前日期
				Date currentDate = CommonUtil.getDate(CommonUtil.date0(beginDate).substring(0, 4) + "-" + CommonUtil.date0(beginDate).substring(4, 6) + "-" + (i + 1), "ISO");
				attendance.setDate(currentDate);
				String kqStr = sheet.getRow(beginRow + 2).getCell(i).getStringCellValue();
				if (CommonUtil.isBlank(kqStr)) {
					// // 判断周六日
					// if (CommonUtil.isEquals(currentDate.getDay(), 0) ||
					// CommonUtil.isEquals(currentDate.getDay(), 6)) {
					// continue;
					// }
					// // 状态：1-正常、2-异常
					// attendance.setStat(new BigDecimal(2));
				} else {
					String[] kqs = kqStr.split(" ");
					if (kqs.length > 1) {
						// 获取该员工的部门信息
						// 方便做匹配
						Department department = departmentMap.get(employeeVo.getDid());

						// 签入时间
						attendance.setCkin(timeft.parse(kqs[0]));
						// 签出时间
						attendance.setCkot(timeft.parse(kqs[kqs.length - 1]));
						if (!hasOut(department.getBgtm(), department.getEdtm(), timeft.parse(kqs[0]), timeft.parse(kqs[1]))) {
							// 状态：1-正常、2-异常
							attendance.setStat(new BigDecimal(1));
						} else {
							// 状态：1-正常、2-异常
							attendance.setStat(new BigDecimal(2));
						}
					} else {
						// 签入时间
						attendance.setCkin(timeft.parse(kqs[0]));
						// 状态：1-正常、2-异常
						attendance.setStat(new BigDecimal(2));
					}
					attendances.add(attendance);
				}
			}
		}
		if (!CommonUtil.isBlank(attendances)) {
			// 删除期间的数据
			Wrapper wrapper2 = Condition.create().between("date", CommonUtil.date(beginDate), CommonUtil.date(endDate));
			this.delete(wrapper2);

			return this.insertBatch(attendances);

		} else {
			// 表格没有要导入的数据
			throw new Exception("表格没有要导入的数据");
		}

	}

	@Override
	public boolean hasOut(Date inDate, Date outDate, Date checkInDate, Date checkOutDate) {
		if (CommonUtil.compareTo(checkInDate, inDate) <= 0 && CommonUtil.compareTo(checkOutDate, outDate) >= 0) {
			return false;
		} else {
			return true;
		}

	}

	@Override
	public List selectCalendar(Wrapper wrapper) {
		return this.baseMapper.selectCalendar(wrapper);
	}

	@Override
	public List selectDetail(Wrapper wrapper) {
		// TODO Auto-generated method stub
		return this.baseMapper.selectDetail(wrapper);
	}

}
